package com.ly.hotel.view;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ly.hotel.R;
import com.ly.hotel.TabHostActivity;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyKeyEventCode;
import com.ly.hotel.common.SharedConfBlacklight;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.model.JxdGuestInfoBean;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.model.SysSettingInfo;
import com.ly.hotel.model.Weather;
import com.ly.hotel.model.WeatherMsg;
import com.ly.hotel.model.WelcomeWordBean;
import com.ly.hotel.msgevent.ActionTimeTickEvent;
import com.ly.hotel.service.BacklightService;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.spainterface.jxd.utils.XmlParseUtils;
import com.ly.hotel.util.DateUtils;
import com.ly.hotel.util.DensityUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.bugtrace.CrashHandler;
import com.ly.hotel.view.floatWindows.ShuaKaFloatWin;
import com.ly.hotel.webagent.HttpRequest;

import de.greenrobot.event.EventBus;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class InitActivity extends Activity {
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private ThisHandler handlerMsg = new ThisHandler(this);
    private MyApplication app;
    private int serverAssessTryTimes = 1;
    private long startTick = System.currentTimeMillis();

    private Button chineseBtn;
    private Button cntBtn;
    private Button usaBtn;
    private int seconds = 6;

    private TextView wHead;
    private TextView wContent;
    private TextView wBottom;

    private String topText;
    private String topTextEn;
    private String detailText;
    private String detailTextEn;
    private String bottomText;
    private String bottomTextEn;
    private boolean isGetWelcome = false;
    private boolean isSelectLang = false;
    private int focusLang;
    private int tyrCount = 8;

    private TextView weatherText;
    private TextView dateText;
    private TextView timeText;
    private ImageView weatherImg;

    private String areaName;
    private String areaNameEn;
    private String defaultMsg;
    private JxdGuestInfoBean guestInfoBean;//捷信达PMS客人信息
    private boolean isGetGusetInfo = true;//true 解析客人信息; false 解析欢迎词
    private final static int HANDLER_INTO_MAIN = 7;// 定时进入主页
    private int mIntoMainSecond = 9;// 进入主页时间


    public class languageinfo {
        String name;
        int resId;
        Locale local;

        languageinfo(String name, int resId, Locale local) {
            this.name = name;
            this.resId = resId;
            this.local = local;
        }
    }

    private static List<languageinfo> languageInfo = new Vector<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME)) {
            HardwareInterface.setGpioDeviceStatus(true, 0); // 按键指示灯绿灯广播
        }

        if (MyApplication.isSelectLang) {
            startTabHost();
        } else {
            Log.d("InitActivity", "进入开机初始化页面");
            setContentView(R.layout.activity_init);
            ProcessWaitingUtil.showProcessDialog(this, "Loading...", 4000);
            EventBus.getDefault().register(this);
            //获取分辨率
            getResolution();
            SharedPreferencesConfig.initSharedPreferencesConfigFile(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!MyApplication.isSelectLang) {

            //		初始化电视硬件相关接口
            HardwareInterface.init(this);
            HardwareInterface.setVolume(Constants.STARTUP_VOLUME);

            //		初始化按键码值
            MyKeyEventCode.init();
            //		初始化服务器IP
            initServerIp();
            app = (MyApplication) this.getApplication();
            app.homeSort = SharedPreferencesConfig.getHomeSort(this);
            MyApplication.interfaceVersion = SharedPreferencesConfig.getInterfaceType(this);
            MyApplication.interfaceServerIp = SharedPreferencesConfig.getInterfaceIp(this);
            MyApplication.interfaceServerPort = SharedPreferencesConfig.getInterfacePort(this);
            defaultMsg = SharedPreferencesConfig.getDefaultMessage(this);
            MyApplication.myRoomNo = SharedPreferencesConfig.getRoomNo(this);
            app.areaId = SharedPreferencesConfig.getAreaId(this);
            app.areaName = SharedPreferencesConfig.getAreaName(this);
            if (!TextUtils.isEmpty(app.areaName) && app.areaName.split(";").length > 1) {
                areaName = app.areaName.split(";")[0];
                areaNameEn = app.areaName.split(";")[1];
            }
            app.initWeatherMsgs();

            Resources resources = getResources();// 获得res资源对象
            Configuration config = resources.getConfiguration();// 获得设置对象
            Log.i("InitActivity", "系统语言:" + config.locale.toString());

            languageInfo.clear();
            languageInfo.add(new languageinfo(getString(R.string.language_chinese), 0, Locale.SIMPLIFIED_CHINESE));
            languageInfo.add(new languageinfo(getString(R.string.language_chinese_traditional), 0, Locale.TRADITIONAL_CHINESE));
            languageInfo.add(new languageinfo(getString(R.string.language_usa), 0, Locale.ENGLISH));

            chineseBtn = findViewById(R.id.chineseLangBtn);
            cntBtn = findViewById(R.id.chineseTraditionalLangBtn);
            usaBtn = findViewById(R.id.usaLangBtn);
            wHead = findViewById(R.id.welcome_head);
            wContent = findViewById(R.id.welcome_content);
            wBottom = findViewById(R.id.welcome_bottom);
            weatherText = findViewById(R.id.area_weather);
            dateText = findViewById(R.id.now_date);
            timeText = findViewById(R.id.now_time);
            weatherImg = findViewById(R.id.weather_img);
            initSysActionNetwork();
            checkBg();

            chineseBtn.setTag(0);
            cntBtn.setTag(1);
            usaBtn.setTag(2);

            chineseBtn.setOnClickListener(onClickListener);
            cntBtn.setOnClickListener(onClickListener);
            usaBtn.setOnClickListener(onClickListener);

            chineseBtn.setOnFocusChangeListener(onFocusListener);
            cntBtn.setOnFocusChangeListener(onFocusListener);
            usaBtn.setOnFocusChangeListener(onFocusListener);

            //获取焦点
            chineseBtn.setFocusable(true);
            chineseBtn.setFocusableInTouchMode(true);
            chineseBtn.requestFocus();

            handlerMsg.sendEmptyMessageDelayed(0, 100);
        } else {
            finish();
        }
    }


    //利用系统的网络变化广播
    private void initSysActionNetwork() {
        IntentFilter intF = new IntentFilter();
        intF.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        MyApplication.getContext().registerReceiver(connectReceiver, intF);
    }

    BroadcastReceiver connectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            ConnectivityManager connectionManager = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                ProcessWaitingUtil.closeProcessDialog();
                if (!TextUtils.isEmpty(MyApplication.interfaceVersion) && !TextUtils.isEmpty(MyApplication.interfaceServerIp)
                        && !TextUtils.isEmpty(MyApplication.interfaceServerPort) && !TextUtils.isEmpty(MyApplication.myRoomNo)) {
                    getWelcomeText();
                    if (!TextUtils.isEmpty(app.areaId) && !TextUtils.isEmpty(areaName) && !TextUtils.isEmpty(areaNameEn)) {
                        getWeather();
                    }
                    getNow();
                }
            }
        }
    };

    //获取服务器时间
    private void getNow() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String URL = MyApplication.getHostResUrl() + "/api/now.json";
                String sendRes = HttpRequest.sendGet(URL, "");

                try {
                    JSONObject jsObj = new JSONObject(sendRes);
                    int code = jsObj.getInt("code");
                    String data = jsObj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        app.nowTime = data;
                        handlerMsg.sendEmptyMessage(4);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //获取天气
    private void getWeather() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String URL = "http://tj.nineton.cn/Heart/index/all";
                String req = "city=" + app.areaId;
                String sendRes = HttpRequest.sendGet(URL, req);
                try {
                    JSONObject jsObj = new JSONObject(sendRes);
                    JSONArray jArr = jsObj.getJSONArray("weather");
                    JSONObject jsObj2 = jArr.getJSONObject(0);
                    JSONObject localObj = jsObj2.getJSONObject("now");

                    WeatherMsg wm = app.getWeatherName(localObj.getString("code"));
                    app.nowWeather = new WeatherMsg(wm.getCode(), wm.getName(), wm.getNameEn(), wm.getImg());
                    app.nowWeather.setTemperature(localObj.getString("temperature"));

                    JSONArray dailyJArr = jsObj2.getJSONArray("future");
                    app.weathers.clear();

                    for (int i = 0; i < dailyJArr.length(); i++) {
                        JSONObject obj = dailyJArr.getJSONObject(i);
                        Weather weather = new Weather();
                        weather.setArea(areaName);
                        weather.setAreaEn(areaNameEn);
                        weather.setDate(obj.getString("date"));
                        weather.setwCode(obj.getString("code1"));
                        weather.setwCode2(obj.getString("code2"));
                        weather.setLow(obj.getString("low"));
                        weather.setHeight(obj.getString("high"));
                        app.weathers.add(weather);
                    }
                    handlerMsg.sendEmptyMessage(5);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //这个时间一分钟来一次，也就是每分钟更新一下时间
    public void onEventMainThread(ActionTimeTickEvent e) {
        showData();
        showWeather();
    }

    private void addDefaultMsg() {
        if (!TextUtils.isEmpty(defaultMsg)) {
            app.setRtMsg(defaultMsg);
        }
    }

    private void showData() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateServer = null;
        String str = app.nowTime;

        try {
            dateServer = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dateServer != null) {
            timeText.setText(DateUtils.getTimeString(dateServer, getResources()));

            if (focusLang == 0 || focusLang == 1) {
                dateText.setText(DateUtils.getDateString(dateServer, "MM月dd日", Locale.CHINESE)/* + "  " + DateUtils.getWeekOfDateZH(dateServer)*/);
            } else {
                dateText.setText(DateUtils.getDateString(dateServer, "MMM d", Locale.ENGLISH) /*+ "  " + DateUtils.getWeekOfDateEN(dateServer)*/);
            }
        }
    }

    //显示天气
    private void showWeather() {
        if (app.nowWeather != null) {
            if (focusLang == 0 || focusLang == 1) {
                weatherText.setText(areaName + "\n" + app.nowWeather.getName() + "  " + app.nowWeather.getTemperature() + " ℃");
                weatherImg.setImageResource(app.nowWeather.getImg());
            } else if (focusLang == 2) {
                weatherText.setText(areaNameEn + "\n" + app.nowWeather.getNameEn() + "  " + app.nowWeather.getTemperature() + " ℃");
                weatherImg.setImageResource(app.nowWeather.getImg());
            }
        }
    }


    public void checkBg() {
        String startupFilePath = SharedPreferencesConfig.getStartUpGuideRes(this);
        String picInfo[] = startupFilePath.split(",");
        String wComePath = "";
        if (picInfo.length >= 1) {
            wComePath = picInfo[0];
        }
        File file = new File(wComePath);

        if (file != null && file.exists()) {
            Bitmap adLogoImage = null;
            if (file.exists()) {
                adLogoImage = BitmapFactory.decodeFile(wComePath);
            }
            if (adLogoImage != null) {
                this.getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(), adLogoImage));
            }
        }
    }

    //获取欢迎词
    private void getWelcomeText() {
        if (MyApplication.interfaceVersion.contains("NM")) {
            final String URL = "http://" + MyApplication.interfaceServerIp + ":"
                    + MyApplication.interfaceServerPort + "/API/index.aspx";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String request = "mid=4001&roomno=" + MyApplication.myRoomNo + "&lang=cn";
                    String str = new String(request.replace(" ", "%20"));
                    Log.i("httpGet", URL + "?" + str);
                    String sendRes = HttpRequest.sendGet(URL, str);
                    Log.i("httpGet", "sendRes:" + sendRes);
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = sendRes;
                    handlerMsg.sendMessage(msg);
                }
            }).start();
        } else if (MyApplication.interfaceVersion.contains("JXD")){
            // 1、客人信息 --> 2、欢迎词
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String url = "http://" + MyApplication.interfaceServerIp + ":" + MyApplication.interfaceServerPort
                            + "/gspmsvodservice/PMSService.asmx" ;
                    String request = getXml(MyApplication.myRoomNo);//获取xml串
                    String sendRes = HttpRequest.sendPostXML(url, request);
                    Log.i("httpGet", "sendRes:" + sendRes);
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = sendRes;
                    handlerMsg.sendMessage(msg);
                }
            }).start();
        } else {
            getTcurrencyWelcome();//获取通用欢迎词
        }
    }

    //获取通用欢迎词
    private void getTcurrencyWelcome(){
        String authToCompany = SharedPreferencesConfig.getAuthToCompany(MyApplication.getContext());
        String roomNo = MyApplication.myRoomNo;
        try {
            authToCompany = URLEncoder.encode(authToCompany,"utf-8");
            roomNo = URLEncoder.encode(roomNo,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String url = Constants.DEFAULT_CLOUD_SERVER + "/api/get-welcome-speech.json";
        final String finalAuthToCompany = authToCompany;
        final String finalRoomNo = roomNo;
        new Thread(new Runnable() {
            @Override
            public void run() {
                String request = "crop=" + finalAuthToCompany + "&roomNo=" + finalRoomNo;
                Log.i("httpGet", url + "?" + request);
                String sendRes = HttpRequest.sendGet(url, request);
                Log.i("httpGet", "sendRes: " + sendRes);
                Message msg = new Message();
                msg.what = 3;
                msg.obj = sendRes;
                handlerMsg.sendMessage(msg);
            }
        }).start();
    }

    private void parseWelcome(String text) {
        if (MyApplication.interfaceVersion.contains("NM")) {
            try {
                JSONObject jsObj = new JSONObject(text);
                String suc = jsObj.getString("success");
                if (suc.equals("true")) {
                    JSONObject arr = jsObj.getJSONObject("data");
                    topText = arr.getString("top") + arr.getString("guestname");
                    topTextEn = arr.getString("top_eng") + " " + arr.getString("guestname_eng");
                    detailText = arr.getString("detail");
                    detailTextEn = arr.getString("detail_eng");
                    bottomText = arr.getString("foot");
                    bottomTextEn = arr.getString("foot_eng");
                    isGetWelcome = true;
                    setWelcomeText();
                } else {
                    String errMsg = jsObj.getString("errorMessage");
                    Log.e("欢迎词", errMsg);
                }
            } catch (JSONException e) {
                //针对飞利浦大电视网络延时
                FLPNetWorkDelay();
            }
        } else if (MyApplication.interfaceVersion.contains("JXD")){
            //欢迎词bean
            WelcomeWordBean wordBean = null;

            if (isGetGusetInfo){//判断解析客人信息还是解析欢迎词
                // 1、解析客人信息
                try {
                    getTcurrencyWelcome();// 2、获取欢迎词
                    isGetGusetInfo = false;
                    guestInfoBean = XmlParseUtils.getInstance().parseWelcomeWord(text);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                // 2、解析欢迎词
                try {
                    ModelBean d = gson.fromJson(text, ModelBean.class);
                    if (d != null && d.getCode() == 200 && d.getData() != null || d.getData().equals("")) {
                        wordBean = parseWelcomeWord(d.getData());
                        String[] heads = wordBean.getHead().split(";");
                        String[] hotelSigns = wordBean.getHotelSign().split(";");
                        String[] usualWelSpes = wordBean.getUsualWelSpe().split(";");
                        String[] sexs = {"先生", "Mr. "};
                        if ((guestInfoBean.getResult() == 200)){
                            //开头敬语
                            if (!TextUtils.isEmpty(guestInfoBean.getGuestName())){//姓名
                                if (guestInfoBean.getGender().equals("female")){//女
                                    sexs[0] = "女士";
                                    sexs[1] = "Ma'am ";
                                }else if (guestInfoBean.getGender().equals("male")){//男
                                    sexs[0] = "先生";
                                    sexs[1] = "Mr. ";
                                }else {//团队客人或是不清性别的客人
                                    topText = heads[0];
                                    if (heads.length > 1) {
                                        topTextEn = heads[1];
                                    }else {
                                        topTextEn = heads[0];
                                    }
                                }
                                topText = getResources().getString(R.string.welcome) + guestInfoBean.getGuestName() + sexs[0] ;
                                topTextEn = "Dear " + sexs[1] + guestInfoBean.getGuestName();
                            }else {
                                //没有获取到客人姓名，用通用的：尊敬的贵宾
                                topText = heads[0];
                                if (heads.length > 1) {
                                    topTextEn = heads[1];
                                }else {
                                    topTextEn = heads[0];
                                }
                            }
                            //设置通用欢迎词和酒店签名
                            setWelcome(usualWelSpes, hotelSigns);

                        }else {
                            //无入住客人信息
                            Log.i("欢迎词",guestInfoBean.getErrorInfo());
                            //使用默认通用的欢迎词
                            topText = heads[0];
                            if (heads.length > 1) {
                                topTextEn = heads[1];
                            }else {
                                topTextEn = heads[0];
                            }

                            //设置通用欢迎词和酒店签名
                            setWelcome(usualWelSpes, hotelSigns);
                        }
                    }else {
                        Log.i("欢迎词",d.getMsg());
                    }
                } catch (Exception e) {
                    //针对飞利浦大电视网络延时
                    FLPNetWorkDelay();
                }
            }

        } else {
            try {
                ModelBean d = gson.fromJson(text, ModelBean.class);
                if (d != null && d.getCode() == 200 && d.getData() != null || d.getData().equals("")) {
                    WelcomeWordBean wordBean = parseWelcomeWord(d.getData());
                    String sexEn = "";
                    String sex = wordBean.getSex();//性别
                    String surname = wordBean.getFirstName();//姓
                    String usuaWelSpe[] = wordBean.getUsualWelSpe().split(";");//通用的
                    String welSpe[] = wordBean.getWelSpe().split(";");//定制的
                    String head[] = wordBean.getHead().split(";");//开头敬语
                    String hotelSign[] = wordBean.getHotelSign().split(";");//酒店签名
                    if (!surname.equals("")) {
                        if (sex.equals("2")) {
                            sexEn = "Ma'am";
                            sex = "女士";
                        } else if (sex.equals("1")) {
                            sexEn = "Mr.";
                            sex = "先生";
                        }
                        topText = getResources().getString(R.string.welcome) + surname + sex;
                        topTextEn = "Distinguished " + sexEn+ " " + surname;
                    } else {
                        if (!TextUtils.isEmpty(wordBean.getHead())) {
                            if (head.length > 1){
                                topText = head[0];
                                topTextEn = head[1];
                            }else {
                                topText = head[0];
                                topTextEn = head[0];
                            }
                        }else {
                            topText = getResources().getString(R.string.welcome) + getResources().getString(R.string.guest);
                            topTextEn = "Distinguished Guests";
                        }
                    }

                    if (!TextUtils.isEmpty(wordBean.getWelSpe())) {
                        if (welSpe.length > 1){
                            detailText = welSpe[0];
                            detailTextEn = welSpe[1];
                        }else{
                            detailText = welSpe[0];
                            detailTextEn = welSpe[0];
                        }
                    } else {
                        if(usuaWelSpe.length > 1){
                            detailText = usuaWelSpe[0];
                            detailTextEn = usuaWelSpe[1];
                        }else{
                            detailText = usuaWelSpe[0];
                            detailTextEn = usuaWelSpe[0];
                        }
                    }
                    if (!TextUtils.isEmpty(wordBean.getHotelSign())) {
                        if (hotelSign.length > 1){
                            bottomText = hotelSign[0];
                            bottomTextEn = hotelSign[1];
                        }else{
                            bottomText = hotelSign[0];
                            bottomTextEn = hotelSign[0];
                        }
                    }
                    isGetWelcome = true;
                    setWelcomeText();
                } else {
                    Log.i("欢迎词", d.getMsg());
                }
            } catch (Exception e) {
                //针对飞利浦大电视网络延时
                FLPNetWorkDelay();
            }
        }
    }

    /*设置通用欢迎词和酒店签名*/
    private void setWelcome(String[] usualWelSpes, String[] hotelSigns) {
        //欢迎词
        if (!TextUtils.isEmpty(usualWelSpes[0])){//中文
            detailText = usualWelSpes[0];
        }
        if (usualWelSpes.length > 1){//英文
            detailTextEn = usualWelSpes[1];
        }else {
            detailTextEn = usualWelSpes[0];
        }
        //酒店签名
        if (!TextUtils.isEmpty(hotelSigns[0])){
            bottomText = hotelSigns[0];
        }
        if (hotelSigns.length > 1){
            bottomTextEn = hotelSigns[1];
        }else {
            bottomTextEn = hotelSigns[0];
        }
        isGetWelcome = true;
        setWelcomeText();
    }

    //针对飞利浦大电视网络延时
    private void FLPNetWorkDelay(){
        if (tyrCount > 0) {
            tyrCount--;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getWelcomeText();
                }
            }, 1000);
        }
    }

    //解析欢迎词相关信息
    private WelcomeWordBean parseWelcomeWord(Object obj){
        WelcomeWordBean welcomeWordBean = new WelcomeWordBean();
        try {
            JSONObject object = new JSONObject(obj.toString());
            welcomeWordBean.setHead(object.getString("head"));
            welcomeWordBean.setHotelSign(object.getString("hotelSign"));
            welcomeWordBean.setUsualWelSpe(object.getString("usualWelSpe"));
            welcomeWordBean.setFirstName(object.getString("firstName"));
            welcomeWordBean.setSex(object.getString("sex"));
            welcomeWordBean.setWelSpe(object.getString("welSpe"));
        } catch (Exception e) {
            Log.i("欢迎词", "欢迎词解析失败" + e.toString());
//            e.printStackTrace();
        }
        return welcomeWordBean;
    }

    //捷信达soap协议xml格式的请求串
    private String getXml(String roomNo){
        String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
                "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<soap:Body>" +
                "<QueryGuestInfo " +
                "xmlns=\"http://www.gshis.com/\">" +
                "<RoomNo>" + roomNo +"</RoomNo>" +
                "</QueryGuestInfo>" +
                "</soap:Body>" +
                "</soap:Envelope>\n";
        return soapXML;
    }

    private void setWelcomeText() {
        if (focusLang == 2) {
            wHead.setText(topTextEn);
            wContent.setText(detailTextEn);
            wBottom.setText(bottomTextEn);
        } else {
            wHead.setText(topText);
            wContent.setText(detailText);
            wBottom.setText(bottomText);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            isSelectLang = true;
            int tag = (Integer) view.getTag();
            switchLanguage(languageInfo.get(tag).local.toString());
            reflashView();
            go();
        }
    };

    private View.OnFocusChangeListener onFocusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus && !isSelectLang) {
                focusLang = (Integer) v.getTag();
                if (isGetWelcome) {
                    setWelcomeText();
                }
                showData();
                showWeather();
            }
        }
    };


    private void reflashView() {
        chineseBtn.setVisibility(View.INVISIBLE);
        usaBtn.setVisibility(View.INVISIBLE);
        cntBtn.setVisibility(View.INVISIBLE);
    }

    private void switchLanguage(String name) {
        Locale locale = Locale.SIMPLIFIED_CHINESE;

        if (name.equals(Locale.ENGLISH.toString())) {
            Log.i("cmd", "设置语言为英文");
            locale = Locale.ENGLISH;
        } else if (name.equals(Locale.SIMPLIFIED_CHINESE.toString())) {
            Log.i("cmd", "设置语言为中文");
            locale = Locale.SIMPLIFIED_CHINESE;
        } else if (name.equals(Locale.TRADITIONAL_CHINESE.toString())) {
            Log.i("cmd", "设置语言为繁体中文");
            locale = Locale.TRADITIONAL_CHINESE;
        }

        Resources resources = getResources();// 获得res资源对象
        Configuration config = resources.getConfiguration();// 获得设置对象
        DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等。
        config.locale = locale;
        resources.updateConfiguration(config, dm);
        MyApplication.currectLocale = locale;
    }

    @SuppressLint("UseSparseArrays")
    private void getResolution() {
        HashMap<Integer, String> Map = new HashMap<>();
        Map.put(120, "ldpi");
        Map.put(160, "mdpi");
        Map.put(240, "hdpi");
        Map.put(320, "xhdpi");
        Map.put(480, "xxhdpi");
        Map.put(640, "xxxhdpi");

        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getMetrics(displayMetrics);
        float density = displayMetrics.density; //得到密度
        float width = displayMetrics.widthPixels;//得到宽度
        float height = displayMetrics.heightPixels;//得到高度
        Integer densityDpi = displayMetrics.densityDpi;

        MyApplication.screenHeight = (int) height;
        MyApplication.screenWidth = (int) width;

        Log.i("InitActivity", "分辨率=" + width + "x" + height + ",密度=" + density + ",Dpi=" + densityDpi + ":" + Map.get(densityDpi));
        DensityUtil.init(getApplicationContext());
    }

    /**
     * 用来判断服务是否运行.
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(50);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().contains(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    public static boolean stopService(Context context, String srvName, Class srvClass) {
        if (isServiceRunning(context, srvName)) {
            boolean ok = false;
            Log.e("init", srvName + "-" + "正在运行,结束之.");
            ok = context.stopService(new Intent(context, srvClass));
            if (!ok) {
                Log.e("init", srvName + "->>停止服务失败！");
                stopService(context, srvName, srvClass);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("init", srvName + "->>停止服务成功！");
                return true;
            }

        } else {
            Log.i("init", srvName + "-" + "没有运行");
        }
        return false;
    }

    //同步本地服务器的数据
    private synchronized void startSpa() {
        if (!app.isStart()) {
            Log.i("initData", "启动service.........");
            Intent intentService = new Intent(this, SPABackService.class);
            this.startService(intentService);
            app.setStart(true);
        }
    }

    private void initBugTrace() {
        CrashHandler catchHandler = CrashHandler.getInstance();
        catchHandler.init(getApplicationContext());
        catchHandler.setHandlerExceptionSendtoCloud();
    }

    // 删除缓存
    private int clearCacheFolder(File dir, long numDays) {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory() && dir.listFiles() != null) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }

                    if (child.lastModified() < numDays) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }

    //清理垃圾文件
    private void clearTmpFolder() {
        int deletedFiles = 0;
        String path = "/data/data/com.ly.hotel/app_spadownload/";
        File dir = new File(path);

        if (dir != null && dir.isDirectory() && dir.listFiles() != null) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.delete()) {
                        Log.i("init", "apk安装包=" + child.getAbsolutePath());
                        deletedFiles++;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.i("init", "删除apk安装包个数=" + deletedFiles);
    }

    private void clearImageCache() {
        int deletedFiles = 0;
        String path = Constants.IMAGE_CACHE_FILE_PATH;
        File dir = new File(path);

        if (dir != null && dir.isDirectory() && dir.listFiles() != null) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.delete()) {
                        deletedFiles++;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.i("init", "删除图片缓存个数=" + deletedFiles);
    }

    private void initSysSettingLocale() {
        Log.i("init-setting", "初始化系统配置");
        SysSettingInfo si = null;
        File f = new File(Constants.SYS_CFG_FILE_PATH);
        if (f.exists()) {
            Log.i("init-setting", "通过本地文件初始化系统设置");
            // 通过本地文件设置按键配置
            InputStreamReader ir;
            try {
                ir = new InputStreamReader(new FileInputStream(Constants.SYS_CFG_FILE_PATH), "utf-8");
                BufferedReader bf = new BufferedReader(ir);

                String tempString = bf.readLine();
                ModelBean dd = gson.fromJson(tempString, ModelBean.class);
                if (dd != null) {
                    si = (SysSettingInfo) dd.getData(SysSettingInfo.class);
                }
                // 一次读一行，读入null时文件结束
                bf.close();

            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }


        if (si != null) {
            Log.i("init-setting", "获取系统设置成功");
            Log.i("init-setting", "留位时间=" + si.getLiuweiWaitTime());
            if (si.getLiuweiWaitTime() >= 0 && si.getLiuweiWaitTime() <= 30) {
                app.setLiuweiTime(si.getLiuweiWaitTime());
            }
            Log.i("init-setting", "屏幕初始亮度=" + si.getDisplay());
            if (si.getDisplay() >= 0 && si.getDisplay() <= 100) {
                SharedConfBlacklight.setAlpha(si.getDisplay() * 2);
                MyApplication.softBlacklightValue = SharedConfBlacklight.getColor(200 - si.getDisplay() * 2, 0, 0, 0);
            }
            Log.i("init-setting", "最大音量=" + si.getMaxVolume());
            if (si.getMaxVolume() >= 5 && si.getMaxVolume() <= 100) {
                if (HardwareInterface.getMaxVolume() != si.getMaxVolume()) {
                    HardwareInterface.setMaxVolume(si.getMaxVolume());
                }
            }
            if (si.getLight() == 0) {
                app.enableServerLed = false;
            }
            if (si.getExtendconf() != null && !si.getExtendconf().equals("")) {
                try {
                    SysConf.sysParse(si.getExtendconf());

                    // 自动进入主页
                    if(SysConf.extendConfGetValue(SysConf.SYS_CONF_AUTO_ENTER, "0").equals("1")){
                        handlerMsg.sendEmptyMessage(HANDLER_INTO_MAIN);
                    }

                    //获取完配置，重新设置一下默认音量
                    Integer volume = Constants.STARTUP_VOLUME;
                    volume = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_STARTUP_VOLUME, Constants.STARTUP_VOLUME + ""));
                    HardwareInterface.setVolume(volume);

                    Log.i("init-setting", "使用本地配置设置默认音量 -> " + volume);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initBtnCfg() {
        app.initBtnItemInfo();
    }

    private void initServerIp() {
        MyApplication.setHost(SharedPreferencesConfig.getSpaServer(this));
        // 这个会在加载服务器文件资源的时候用到
        MyApplication.setHostResUrl(MyApplication.getHost() + "/");// premier-sys
        MyApplication.hostMyResUrl = MyApplication.getHost() + "/upload/myres/";
    }

    private void go() {
        long tick = System.currentTimeMillis() - startTick;
        Log.i("InitActivity", "在语言界面停留时间:" + tick);

        //延时进入主界面
        if (handlerMsg.hasMessages(2)) {
            handlerMsg.removeMessages(2);
        }

        if (tick < seconds * 1000) {
            //延时一下，免得加载失败
            handlerMsg.sendEmptyMessageDelayed(2, 1000);
        } else {
            handlerMsg.sendEmptyMessage(2);
        }

    }

    private void initBacklight() {
        String enable = SysConf.extendConfGetValue(SysConf.SYS_CONF_BL_ENABLE, "0");
        if (enable.equals("1")) {
            //初始化背光控制
            Intent i = new Intent(getApplicationContext(), BacklightService.class);
            startService(i);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //跳转主Activity
    public void startTabHost() {
        MyApplication.isSelectLang = true;
        Intent intent = new Intent();
        intent.setClass(this, TabHostActivity.class);
        startActivity(intent);
        finish();
    }

    private class ThisHandler extends Handler {
        private WeakReference<InitActivity> wrActivity;

        public ThisHandler(InitActivity activity) {
            wrActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message message) {
            InitActivity act = wrActivity.get();
            if (act != null) {
                switch (message.what) {
                    case 0://等待网络
                        if (MyApplication.serverAssess || act.serverAssessTryTimes <= 0) {
                            removeMessages(1);
                            sendEmptyMessageDelayed(1, 100);
                        } else {
                            act.serverAssessTryTimes--;
                            sendEmptyMessageDelayed(0, 1000);
                        }

                        break;

                    case 1:
                        Log.e("InitActivity", "初始化事件！");
                        act.initSysSettingLocale();

                        //启动主服务
                        act.startSpa(); //启动主服务
                        act.initBacklight();//初始化背光服务，必须先调用过initSysSettingLocale()

                        act.initBugTrace();            //初始化bug上报日志
                        act.clearCacheFolder(act.getCacheDir(), System.currentTimeMillis());
                        act.clearTmpFolder();
                        act.clearImageCache();
                        break;

                    case 2://进入主页
                        act.initBtnCfg();                //这个的初始化和语言有关，必须在语言设置完成后初始化
                        Intent intentService = new Intent(act, ShuaKaFloatWin.class);
                        act.startService(intentService);
                        act.startTabHost();
                        break;
                    case 3:
                        act.parseWelcome(message.obj.toString());
                        break;
                    case 4:
                        act.addDefaultMsg();
                        act.showData();
                        break;
                    case 5:
                        act.showWeather();
                        break;
                    case 6:

                        break;
                    case HANDLER_INTO_MAIN:
                        mIntoMainSecond --;
                        if(mIntoMainSecond > 0){
                            handlerMsg.sendEmptyMessageDelayed(HANDLER_INTO_MAIN,1000);
                        }else {
                            chineseBtn.performClick();
                        }
                        break;
                }
            }
        }
    }
}
